home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / glibc108.zip / glibc108 / manual / examples / pipe.c < prev    next >
C/C++ Source or Header  |  1994-02-16  |  1KB  |  67 lines

  1. #include <sys/types.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. /* Read characters from the pipe and echo them to @code{stdout}.  */
  7.  
  8. void 
  9. read_from_pipe (int file)
  10. {
  11.   FILE *stream;
  12.   int c;
  13.   stream = fdopen (file, "r");
  14.   while ((c = fgetc (stream)) != EOF)
  15.     putchar (c);
  16.   fclose (stream);
  17. }
  18.  
  19. /* Write some random text to the pipe. */
  20.  
  21. void 
  22. write_to_pipe (int file)
  23. {
  24.   FILE *stream;
  25.   stream = fdopen (file, "w");
  26.   fprintf (stream, "hello, world!\n");
  27.   fprintf (stream, "goodbye, world!\n");
  28.   fclose (stream);
  29. }
  30.  
  31. int
  32. main (void)
  33. {
  34.   pid_t pid;
  35.   int mypipe[2];
  36.  
  37. /*@group*/
  38.   /* Create the pipe. */
  39.   if (pipe (mypipe))
  40.     {
  41.       fprintf (stderr, "Pipe failed.\n");
  42.       return EXIT_FAILURE;
  43.     }
  44. /*@end group*/
  45.  
  46.   /* Create the child process. */
  47.   pid = fork ();
  48.   if (pid == (pid_t) 0)
  49.     {
  50.       /* This is the child process. */
  51.       read_from_pipe (mypipe[0]);
  52.       return EXIT_SUCCESS;
  53.     }
  54.   else if (pid < (pid_t) 0)
  55.     {
  56.       /* The fork failed. */
  57.       fprintf (stderr, "Fork failed.\n");
  58.       return EXIT_FAILURE;
  59.     }
  60.   else
  61.     {
  62.       /* This is the parent process. */
  63.       write_to_pipe (mypipe[1]);
  64.       return EXIT_SUCCESS;
  65.     }
  66. }
  67.